﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;

namespace ZSoft.PushServices.Server.Infra.Events
{
    public static class EventManager
    {
        private static List<Type> _eventTypes;
        private static List<IEventHandler> _handlers;

        public static void ExecuteHandlers(AppEventType eventType)
        {
            Handlers.Where(t => t.EventType == eventType).ForEach(h => h.Execute());
        }

        public static List<IEventHandler> Handlers
        {
            get
            {
                if (_handlers == null)
                {
                    _handlers = new List<IEventHandler>();

                    HandlerTypes.ForEach(t => _handlers.Add(Activator.CreateInstance(t) as IEventHandler));
                }

                return _handlers;
            }
        }

        public static List<Type> HandlerTypes
        {
            get
            {
                if (_eventTypes == null)
                {
                    Type interfaceType = typeof(IEventHandler);

                    _eventTypes = Assembly.GetExecutingAssembly()
                        .GetTypes()
                        .Where(t => !t.IsInterface && interfaceType.IsAssignableFrom(t))
                        .ToList();
                }

                return _eventTypes;
            }
        }
    }
}